﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Purchases;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class PurchaseRequest : RibbonForm
    {
        public PurchaseRequest()
        {
            InitializeComponent();
        }

        #region Properties
        public string ConnectionString { get; set; }
        public string ActiveUserID { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string DefaultWarehouse { get; set; }

        public string UserName { get; set; }
        public DataTable RequestLineItems { get; set; }
        public string DefaultPriceList { get; set; }
        public string VATCode { get; set; }
        public string VATRate { get; set; }
        public bool IsInclusive { get; set; }
        public string Department { get; set; }
        #endregion

        #region Initialization


        private static DataTable GetTable()
        {
            DataTable table = new DataTable();

            table.Columns.Add("ItemCode", typeof(string));
            table.Columns.Add("ItemDesc", typeof(string));
            table.Columns.Add("UoM", typeof(string));
            table.Columns.Add("Qty", typeof(double));
            
            return table;

        }

        void InitializeSeries()
        {

            string _PR_SERIES = "6";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            lblValidUntilDeliveryDate.Text = "Date Needed:";
            if (oSeries.IsAutoNumber(_PR_SERIES) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();
 
        }
        
        #endregion

        #region Functions
        public void BindDepartment()
        {
            DepartmentManager oManager = new DepartmentManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            cboDepartment.Properties.Columns.Clear();
            cboDepartment.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DeptName"));
            cboDepartment.Properties.DisplayMember = "DeptName";
            cboDepartment.Properties.ValueMember = "DeptName";

            cboDepartment.Properties.DataSource = oManager.GetDepartment();
            cboDepartment.Properties.ShowHeader = false;
            cboDepartment.Refresh();

            oManager.Close();
        }

        public void BindDivision()
        {
            CardDivisionManager oManager = new CardDivisionManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            cboDivision.Properties.Columns.Clear();
            cboDivision.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("DivName"));
            cboDivision.Properties.DisplayMember = "DivName";
            cboDivision.Properties.ValueMember = "DivName";

            cboDivision.Properties.DataSource = oManager.GetDivision();
            cboDivision.Properties.ShowHeader = false;
            cboDivision.Refresh();

            oManager.Close();
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();
            
            cboLocation.Visible = false;
            cboLocation.Properties.DataSource = oTable;
            cboLocation.Properties.DisplayMember = "Dscription";
            cboLocation.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboLocation.Properties.Columns.Add(col);
            cboLocation.Properties.ShowHeader = false;
            cboLocation.Visible = true;
            oManager.Close();
        }


        void BindEntities()
        {
            EntityManager oManager = new EntityManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetEntities();

            cboEntities.Visible = false;
            cboEntities.Properties.DataSource = oTable;
            cboEntities.Properties.DisplayMember = "EntityDescription";
            cboEntities.Properties.ValueMember = "EntityDescription";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("EntityDescription", "EntityDescription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
            cboEntities.Properties.Columns.Clear();
            cboEntities.Properties.Columns.Add(col);
            cboEntities.Properties.ShowHeader = false;
            cboEntities.Visible = true;
            oManager.Close();
        }

        public void PrintPreview()
        {
            PRNT_PR oPrint = new PRNT_PR();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }

        void EnableControls()
        {
            cboEntities.Enabled = true;
            cboLocation.Enabled = true;            
            cboDivision.Enabled = true;
            cboDepartment.Enabled = true;
            txtCardCode.Enabled = true;
            txtCardName.Enabled = true;
            txtReference.Enabled = true;
            txtShipTo.Enabled = true;
            txtDocumentNumber.Enabled = true;
            dtPostDate.Enabled = true;
            dtDeliveryDate.Enabled = true;
            dtDocDate.Enabled = true;
            txtRemarks.Enabled = true;
            
            btnAdd.Enabled = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                if (oColumn.Name == "Code" || oColumn.Name == "Quantity" || oColumn.Name == "Free")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }
            }

        }

        void DisableControls()
        {
            cboEntities.Enabled = false;
            cboLocation.Enabled = false;
            cboDivision.Enabled = false;
            cboDepartment.Enabled = false;
            txtCardCode.Enabled = false;
            txtCardName.Enabled = false;
            txtReference.Enabled = false;
            txtShipTo.Enabled = false;
            txtDocumentNumber.Enabled = false;
            dtPostDate.Enabled = false;
            dtDeliveryDate.Enabled = false;
            dtDocDate.Enabled = false;
            
            
            txtRemarks.Enabled = false;
            btnAdd.Enabled = false;
            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                oColumn.OptionsColumn.AllowEdit = false;
            }
            
        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _DOCTYPE = "6";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_DOCTYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_DOCTYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void RemoveBlankLastRowFirst()
        {
            try
            {
                int iCount = -1;
                gridView1.MoveLast();

                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                string sItemCode = "";


                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView1.DeleteRow(iCount);
                }
            }
            catch
            {
            }

        }

        public void ShowSearch()
        {
            FND_PR oSearchDocument = new FND_PR();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                PurchaseRqtManager oManager = new PurchaseRqtManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetPurchaseRequest(sDocumentNumber);
             

                #region Header 
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
                dtDeliveryDate.EditValue = (DateTime)oRow["DueDate"];
                dtDocDate.EditValue = (DateTime)oRow["DocDate"];
                cboDepartment.EditValue = (string)oRow["Department"];
                cboDivision.EditValue = (string)oRow["Division"];
                cboEntities.EditValue = (string)oRow["EntityCode"];

                cboEntities.ClosePopup();
                cboDivision.ClosePopup();
                cboDepartment.ClosePopup();
                cboLocation.ClosePopup();

                txtCardCode.EditValue = oRow["CardCode"].ToString();
                AddressBookManager oCardManager = new AddressBookManager();
                oCardManager.Connection = oManager.Connection;
                this.DefaultPriceList = oCardManager.GetPriceListCode(txtCardCode.Text);
                txtCardName.EditValue = oRow["CardName"].ToString();
                txtReference.EditValue = oRow["Reference"].ToString();
                txtShipTo.EditValue = oRow["ShipTo"].ToString();
                
                txtRemarks.EditValue = oRow["Remarks"].ToString();

                cboLocation.EditValue = oRow["Location"].ToString();
            

                if (oRow["VATCode"] != DBNull.Value)
                {
                    this.VATCode = oRow["VATCode"].ToString();
                }

                this.VATRate = oRow["VATRate"].ToString();

                if (oRow["IsVATInclusive"] != DBNull.Value)
                {

                    if (oRow["IsVATInclusive"].ToString() == "Y")
                    {
                        this.IsInclusive = true;
                    }
                    else
                    {
                        this.IsInclusive = false;
                    }
                }

                
                #endregion

                #region Line Items
                this.RequestLineItems = oManager.GetPRLineItems(sDocumentNumber);
                gridControl1.DataSource = this.RequestLineItems;
                gridControl1.Refresh();

                #endregion

                oManager.Close();

                btnAdd.Text = "Update";



            }


            
        }

        void CancelOrder(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to cancel this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                PurchaseRqtManager oManager = new PurchaseRqtManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CancelRequest(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Canceled";
            }

        }

        void PostRequest(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to post this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                PurchaseRqtManager oManager = new PurchaseRqtManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.PostRequest(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Posted";
               
            }
        }

        void CloseRequest(string sDocNumber)
        {
            if (MessageBox.Show("Are you sure you want to close this document?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                PurchaseRqtManager oManager = new PurchaseRqtManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                oManager.CloseRequest(sDocNumber);
                oManager.Close();

                txtStatus.Text = "Closed";
               
            }
        }
        #endregion

        public int ObjectType { get { return 6; } }

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }


        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;


            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;

            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }

        
        #region Form Events

        private void PurchaseRequest_Load(object sender, EventArgs e)
        {
           
            
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];

                if (e.KeyCode == Keys.Delete)
                {
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            if (gridView1.IsLastRow)
                            {
                                string sItemCode = "";

                                oRow = gridView1.GetSelectedRows();
                                iCount = oRow[0];
                                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();


                                if (sItemCode != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                    gridView1.AddNewRow();
                                }

                                
                                gridView1.RefreshData();

                            }
                            else
                            {

                                string sItemCode = "";


                                oRow = gridView1.GetSelectedRows();
                                iCount = oRow[0];
                                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                                if (sItemCode != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                }

                                gridView1.RefreshData();
                            }
                        }
                    }
                }
                
                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";
                        oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "" && (txtStatus.Text == "Draft"))
                        {
                            gridView1.AddNewRow();

                            gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
                            gridView1.ShowEditor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void btnSearchItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int iCount = -1;
            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];

            FND_ITM_PR _FindItem_PUR = new FND_ITM_PR();

            _FindItem_PUR.ConnectionString = this.ConnectionString;
            _FindItem_PUR.ShowDialog();

            if (_FindItem_PUR.ItemCode != null)
            {
                if (_FindItem_PUR.ItemCode.Trim() != "")
                {

                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], _FindItem_PUR.ItemCode);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], _FindItem_PUR.Description);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], _FindItem_PUR.UoM);
                    
                    
                }
                else
                {
                    gridView1.CancelUpdateCurrentRow();
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }
                }
            }
            else
            {
                gridView1.CancelUpdateCurrentRow();
                if (gridView1.RowCount <= 0)
                {
                    gridView1.AddNewRow();
                }
            }

            _FindItem_PUR.Dispose();
        }

        private void btnSearchItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            
            if (e.KeyCode == Keys.Enter)
            {
               
            }
        }

        private void txtQty_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                
            }
        }

        bool InComplete()
        {
            bool _Incomplete = false;

            if (txtDocumentNumber.Text == "") { return true; }
            if (txtCardCode.Text == "") { return true; }
            if (txtCardName.Text == "") { return true; }



            foreach (DataRow oRow in this.RequestLineItems.Rows)
            {
                double _Qty = Convert.ToDouble(oRow["Qty"]);

                if (_Qty == 0)
                {
                    return true;
                }
            }

            return _Incomplete;

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            PurchaseRqtManager oManager = new PurchaseRqtManager();
            PurchaseRqtUnit oUnit = new PurchaseRqtUnit();
            RemoveBlankLastRowFirst();
            if (InComplete() == false)
            {
                
                if (btnAdd.Text != "Update")
                {
                    #region Header Sales Quote

                    txtDocumentNumber.Text = GetNewSeries();
                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;


                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    
                    
                    oUnit.Location = cboLocation.EditValue.ToString();
                    

                    if (cboDivision.Text != null)
                    {
                        oUnit.Division = cboDivision.Text.ToString();
                    }
                    else
                    {
                        oUnit.Division= "";
                    }

                    oUnit.Department = cboDepartment.Text.ToString();
                    oUnit.EntityCode = cboEntities.Text.ToString();
                    oUnit.Remarks = txtRemarks.Text.ToString();


                    #endregion

                    oUnit.LineItems = this.RequestLineItems;

                    #region Adding Part
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();
                    oManager.AddPurchaseRequest(oUnit);
                    oManager.Close();
                    #endregion

                    btnAdd.Text = "Update";

                    MessageBox.Show("Saving document is successful!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {

                    #region Header Sales Quote

                    oUnit.DocumentNumber = txtDocumentNumber.Text;
                    oUnit.DocumentStatus = txtStatus.Text;
                    oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                    oUnit.DueDate = (DateTime)dtDeliveryDate.EditValue;
                    oUnit.DocDate = (DateTime)dtDocDate.EditValue;

                    oUnit.CardCode = txtCardCode.Text;
                    oUnit.CardName = txtCardName.Text;
                    oUnit.Reference = txtReference.Text;
                    oUnit.ShipTo = txtShipTo.Text;
                    
                    
                    oUnit.Location = cboLocation.EditValue.ToString();
                    
                    if (cboDivision.Text != null)
                    {
                        oUnit.Division = cboDivision.Text.ToString();
                    }
                    else
                    {
                        oUnit.Division = "";
                    }


                    oUnit.Department = cboDepartment.EditValue.ToString();
                    oUnit.EntityCode = cboEntities.EditValue.ToString();
                    oUnit.Remarks = txtRemarks.Text.ToString();

                    

                    #endregion

                    oUnit.LineItems = this.RequestLineItems;

                    #region Updating Portion
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();
                    oManager.UpdatePurchaseRequest(oUnit);
                    oManager.Close();
                    #endregion

                    MessageBox.Show("Updating document is successful!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Please complete the required information, zero value in the quantity is also not allowed in the Line Items!!!!!!", "Sales Order", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        
        #endregion

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtDocumentNumber.Text != "##########" )
            {
                if (txtStatus.Text == "Draft")
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                    {
                        PostRequest(txtDocumentNumber.Text);
                    }

                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CancelOrder(txtDocumentNumber.Text);
                    }
                }
                else
                {
                    if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                    {
                        CloseRequest(txtDocumentNumber.Text);
                    }
                }
            }
            
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
                btnCopyToPO.Visible = false;
            }
            if (txtStatus.Text == "Canceled" || txtStatus.Text == "Closed")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
                btnCopyToPO.Visible = false;
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                btnCopyToPO.Visible = true;
            }

            if (txtStatus.Text == "Open")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
                DisableControls();
                btnCopyToPO.Visible = true;
            }
        }

        private void btnCopyToPO_Click(object sender, EventArgs e)
        {
            PurchaseOrder oNewPO = new PurchaseOrder();

            oNewPO.MdiParent = this.MdiParent;
            //txtCode
            //oNewPO.CardCode = txtCardCode.Text;
            //oNewPO.CardName = txtCardName.Text;

            
            oNewPO.ConnectionString = this.ConnectionString;
            oNewPO.ActiveUserID = this.ActiveUserID;
            oNewPO.DefaultPriceList = this.DefaultPriceList;
            oNewPO.VATCode = this.VATCode;
            oNewPO.VATRate = this.VATRate;
            oNewPO.IsInclusive = this.IsInclusive;

            oNewPO.BindEntities();

            oNewPO.BindWarehouse();
            
            oNewPO.Warehouse = cboLocation.EditValue.ToString();
            oNewPO.IsMultipleWarehouse = this.IsMultipleWarehouse;
            
            oNewPO.RequestedBy = txtCardName.Text;
            oNewPO.Reference = txtDocumentNumber.Text;
            oNewPO.ShipTo = txtShipTo.Text;
            oNewPO.PostingDate = (DateTime)dtPostDate.EditValue;
            oNewPO.DeliveryDate = (DateTime)dtDeliveryDate.EditValue;
            oNewPO.DocumentDate = (DateTime)dtDocDate.EditValue;
            oNewPO.Department = cboDepartment.Text;
            oNewPO.EntityCode = cboEntities.Text;
            oNewPO.Division = cboDivision.Text;
            oNewPO.Remarks = txtRemarks.Text;
            
            oNewPO.PurchaseOderLineItems = new DataTable();
            oNewPO.PurchaseOderLineItems = oNewPO.GetTable();

            foreach (DataRow oRow in this.RequestLineItems.Rows)
            {
                DataRow lineRow = oNewPO.PurchaseOderLineItems.NewRow();

                lineRow["ItemCode"] = oRow["ItemCode"];
                lineRow["ItemDesc"] = oRow["ItemDesc"];
                lineRow["UoM"] = oRow["UoM"];
                lineRow["Qty"] = oRow["Qty"];
                lineRow["UnitPrice"] = 0;
                lineRow["IsFree"] = false;
                lineRow["DiscPrcnt"] = 0;
                lineRow["Discount"] = 0;
                lineRow["TotalLineDisc"] = 0;
                lineRow["Amount"] = 0;

                oNewPO.PurchaseOderLineItems.Rows.Add(lineRow);
            }

            oNewPO.Show();
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "")
                e.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void PurchaseRequest_Shown(object sender, EventArgs e)
        {
            BindDivision();
            BindDepartment();

            txtCardCode.Text = this.ActiveUserID.ToUpper().ToString();
            txtCardName.Text = this.UserName.ToString();
            cboDepartment.Text = this.Department;

            cboEntities.ClosePopup();
            cboDivision.ClosePopup();
            cboDepartment.ClosePopup();
            cboLocation.ClosePopup();

            dtPostDate.EditValue = System.DateTime.Now;
            dtDeliveryDate.EditValue = System.DateTime.Now;
            dtDocDate.EditValue = System.DateTime.Now;


            this.VATRate = "0";
            this.VATCode = "NON-VAT";


            BindWarehouse();
            BindEntities();
            cboLocation.EditValue = this.DefaultWarehouse;
            if (this.IsMultipleWarehouse == false)
            {
                cboLocation.Enabled = false;
            }

            if (this.RequestLineItems == null)
            {
                this.RequestLineItems = GetTable();
            }

            gridControl1.DataSource = this.RequestLineItems;
            gridControl1.Refresh();

            if (gridView1.DataRowCount <= 0)
            {
                gridView1.AddNewRow();
                gridControl1.Select();
                gridView1.FocusedColumn = gridView1.Columns["Qty"];
                gridView1.ShowEditor();
            }

            InitializeSeries();
            gridControl1.Select();
            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
            gridView1.ShowEditor();


            txtRemarks.Focus();

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }


            cboEntities.ClosePopup();
            cboDivision.ClosePopup();
            cboDepartment.ClosePopup();
            cboLocation.ClosePopup();
        }

        private void btnSearchItemCode_Leave(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

            try
            {
                string sItemCode = oButtonEdit.Text;
                ItemManager oManager = new ItemManager();

                if (sItemCode != "")
                {
                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetPurItmsByCode(sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Dscription"].ToString(),
                                        UoM = row["UoM"].ToString()
                                    };


                        int iCount = -1;
                        int[] oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];

                        string sVAT = this.VATCode.Trim() != "" ? this.VATCode : "N/A";
                       
                        int iRowIndex = gridView1.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }
                        foreach (var oUnit in items)
                        {
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemDesc"], oUnit.Dscription);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
                        }
                        #endregion

                        gridView1.FocusedColumn = gridView1.Columns["Qty"];

                        gridView1.ShowEditor();

                        
                    }
                    else
                    {
                        MessageBox.Show("No item found in the master list!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        oButtonEdit.Text = "";
                        oButtonEdit.Focus();
                    }
                }
            }
            catch
            {
            }
        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"], ((DevExpress.XtraEditors.TextEdit)sender).Text);
        }

        private void txtCardName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_EMPLOYEE oSearch = new FND_EMPLOYEE();
            EmployeeManager oManger = new EmployeeManager();
            oSearch.ConnectionString = this.ConnectionString;
            oSearch.ShowDialog();


            string sEmpID = oSearch.EmployeeID;
            string sEmpName = oSearch.EmployeeFullName;
            string sDept = oSearch.EmployeeDepartment;
            txtCardName.Text = sEmpName;
            cboDepartment.EditValue = sDept;
            cboDepartment.ClosePopup();
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

        private void PurchaseRequest_Resize(object sender, EventArgs e)
        {
            try
            {
                txtDocumentNumber.Left = this.Width - 150;
                txtStatus.Left = this.Width - 150;
                dtPostDate.Left = this.Width - 150;
                dtDeliveryDate.Left = this.Width - 150;
                dtDocDate.Left = this.Width - 150;
                txtCardCode.Left = this.Width - 150;

                lblDocStatus.Left = this.Width - 250;
                lblDocNo.Left = this.Width - 250;
                lblPostDate.Left = this.Width - 250;
                lblValidUntilDeliveryDate.Left = this.Width - 250;
                lblDocumentDate.Left = this.Width - 250;
                lblBPCode.Left = this.Width - 250;

                gridControl1.Width = this.Width - 38;

            }
            catch
            {
            }
        }

        

    }
}
